<template>
  <ProTable
    ref="tableRef"
    :fetchListApi="listPost"
    :columns="columns"
    :row-selection="rowSelection"
    row-key="postId"
    :onValuesChange="onValuesChange"
  >
    <template #toolbars>
      <Row class="w-full mr-3">
        <Col :span="16">
          <Space>
            <b-button icon="add" code="system:post:add" @click="onAdd"
              >新增</b-button
            >
            <b-button
              icon="delete"
              @click="onDelete(null)"
              :disabled="!selectKeys?.length"
              code="system:post:remove"
              >删除</b-button
            >
          </Space>
        </Col>
        <Col :span="8" class="text-right content-center">
          <Space>
            <b-button icon="export" @click="onExport" code="system:post:export"
              >导出</b-button
            >
          </Space>
        </Col>
      </Row>
    </template>
    <template #operation="{ record }">
      <b-button icon="detail" type="link" @click="() => onView(record)"
        >详情</b-button
      >
      <b-button
        icon="delete"
        type="link"
        code="system:post:remove"
        @click="() => onDelete(record)"
        >删除</b-button
      >
    </template>
    <template #status="{ column, record }">
      <Tag :color="record.status == '0' ? 'success' : 'error'"
        >{{ record.status == '0' ? '正常' : '停用' }}
      </Tag>
    </template>
  </ProTable>
  <FormModal :items="items"> </FormModal>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';
import { hasPermission } from '@/permission';
import { Col, Modal, Row, Space, Tag } from 'ant-design-vue';
import dayjs from 'dayjs';
import { ProFormProps } from '@/components/ProForm';
import { ProTable, ProTableProps } from '@/components/ProTable/index';
import { useFormModal } from '@/hooks/formModal';
import { download } from '@/utils/utils';
import {
  addPost,
  delPost,
  exportPost,
  listPost,
  updatePost,
} from '@/api/system';

const tableRef = ref();

const init = () => {};

init();

const selectKeys = ref<any[]>([]);
const rowSelection = computed<ProTableProps['rowSelection']>(() => {
  return {
    onChange(values, all) {
      selectKeys.value = all as any[];
    },
  };
});

const columns = computed<ProTableProps['columns']>(() => [
  {
    title: '岗位编号',
    dataIndex: 'postId',
    hideInSearch: true,
  },
  {
    title: '岗位编码',
    dataIndex: 'postCode',
  },
  {
    title: '岗位名称',
    dataIndex: 'postName',
  },
  {
    title: '岗位排序',
    dataIndex: 'postSort',
    hideInSearch: true,
  },
  {
    title: '状态',
    dataIndex: 'status',
    valueEnum: {
      '0': '正常',
      '1': '停用',
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    hideInSearch: true,
  },
  {
    title: '操作',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    width: 160,
  },
]);

const items = computed<ProFormProps['items']>(() => [
  {
    label: '岗位名称',
    type: 'input',
    field: 'postName',
    rules: [{ required: true, message: '请输入岗位名称', trigger: 'blur' }],
    props: {
      placeholder: '请输入岗位名称',
    },
  },
  {
    label: '岗位编码',
    type: 'input',
    rules: [{ required: true, message: '请输入岗位编码', trigger: 'blur' }],
    field: 'postCode',
    props: {
      placeholder: '请输入岗位编码',
    },
  },
  {
    label: '岗位顺序',
    type: 'number',
    rules: [{ required: true, message: '请输入岗位顺序', trigger: 'blur' }],
    field: 'postSort',
    props: {
      min: 1,
      placeholder: '请输入岗位顺序',
    },
  },
  {
    label: '岗位状态',
    type: 'radio',
    field: 'status',
    rules: [{ required: true, message: '请选择岗位状态', trigger: 'blur' }],
    props: {
      options: [
        { label: '正常', value: '0' },
        { label: '停用', value: '1' },
      ],
    },
  },
  {
    label: '备注',
    type: 'textarea',
    field: 'remark',
    props: {
      placeholder: '请输入备注',
      rows: 4,
    },
  },
]);

const { FormModal, open } = useFormModal({ size: 'small' });

const onAdd = async () => {
  open({
    title: '新增',
    defaultValue: {},
    serviceApi: async (params: any): Promise<any> => {
      await addPost(params);
      sleep(() => tableRef.value.refresh());
    },
  });
};

const onView = async (record: any) => {
  open({
    title: (type) => (type === 'info' ? '详情' : '编辑'),
    modalType: 'info',
    defaultValue: {
      ...record,
    },
    hasEditPermission: hasPermission('system:post:edit'),
    serviceApi: async (params: any): Promise<any> => {
      await updatePost({
        ...params,
        id: record.id,
      });
      sleep(() => tableRef.value.refresh());
    },
  });
};

const sleep = (cb) => {
  setTimeout(() => {
    cb();
  }, 500);
};

const onDelete = async (record: any) => {
  const ids = record
    ? record.postId
    : selectKeys.value.map((item) => item.postId).join(',');
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选项？`,
    onOk: async () => {
      await delPost(ids);
      sleep(() => tableRef.value.refresh());
      selectKeys.value = [];
    },
  });
};

const searchParams = ref({});
const onValuesChange = (values: any) => {
  searchParams.value = Object.assign(searchParams.value, values);
};
const onExport = async () => {
  const res = await exportPost(searchParams.value);
  download(
    res as unknown as Blob,
    `data_${dayjs().format('YYYY-MM-DD HH:mm:ss')}.xlsx`,
  );
};
</script>
